<template>
  <div style="padding: 0 17px">
    <Breadcrumb/>
    <div style="display: flex">
      <div style="margin-top: 20px;" :style="{ width: '50%'}">
        <el-button-group style="font-size: 12px;">
          <el-button style="width: 140px" :disabled="this.retrieve === 0" type="primary" @click="checkRetrieve">组织检索</el-button>
          <el-button style="width: 140px" :disabled="this.retrieve === 1" type="primary" @click="checkRetrieve">单位检索</el-button>
        </el-button-group>
        <el-input
            style="margin-top: 20px;width: 280px"
            placeholder="输入关键字进行过滤"
            v-model="filterText">
        </el-input>
        <div v-if="this.retrieve === 0" style="width: 280px; margin-top: 20px; height: calc(100vh - 250px); overflow-y: auto; overflow-x: auto;">
          <el-tree
              class="filter-tree"
              :data="treeData"
              :props="defaultProps"
              check-on-click-node
              highlight-current
              node-key="id"
              @node-click="currentChanged"
              :filter-node-method="filterNode"
              ref="tree"
              style="min-width: 280px; white-space: nowrap;">
            <template #default="{ node }">
              <span :title="node.label">{{ node.label }}</span>
            </template>
          </el-tree>
        </div>
        <div v-if="this.retrieve === 1" style="width: 280px; margin-top: 20px; height: calc(100vh - 250px); overflow-y: auto; overflow-x: auto;">
          <el-tree
                  class="filter-tree"
                  :data="clientTreeData"
                  :props="clientDefaultProps"
                  check-on-click-node
                  highlight-current
                  node-key="id"
                  @node-click="currentClientChanged"
                  :filter-node-method="filterNode"
                  ref="tree"
                  style="min-width: 280px; white-space: nowrap;">
            <template #default="{ node }">
              <span :title="node.label">{{ node.label }}</span>
            </template>
          </el-tree>
        </div>
      </div>
      <div style="width: 100%;color: #909399;font-size: 12px;">
        <div style="margin-top: 20px;color: #fff;font-size: 12px">
          <el-button-group>
            <el-button type="primary" :disabled="currentData.level===7||currentData.level===0||currentData.level===1||currentData.level===2" @click="addNode">添加{{ addText }}</el-button>
            <el-button type="primary" :disabled="currentData.id===undefined||currentData.level===0||currentData.level===1||currentData.level===2||currentData.level===3" @click="editNode">编辑</el-button>
            <el-button type="primary" :disabled="currentData.id===undefined||currentData.level===0||currentData.level===1||currentData.level===2||currentData.level===3" @click="deleteNode">删除</el-button>
            <el-button type="success" style="" @click="exportOrginData">导出组织</el-button>
          </el-button-group>
          <el-button type="primary" style="margin-left: 10px" @click="addItem">添加单位</el-button>
          <el-input :disabled="currentData.id===undefined" v-model="searchName" placeholder="输入名称搜索"
                    style="width: 200px;height: 33px;margin-left:15px;font-size: 13px;" clearable></el-input>
          <el-input :disabled="currentData.id===undefined" v-model="searchAddress" placeholder="输入地址搜索"
                    style="width: 200px;height: 33px;margin-left: 15px;font-size: 13px;" clearable></el-input>
          <el-button :disabled="currentData.id===undefined" v-if="this.retrieve === 0" style="margin-left: 15px" type="primary" @click="load">搜索
          </el-button>
          <el-button v-if="this.retrieve === 1 && this.currentClientData === null" style="margin-left: 15px" type="primary" @click="getClientPage">搜索
          </el-button>
          <el-button v-if="this.retrieve === 1 && this.currentClientData !== null" style="margin-left: 15px" type="primary" @click="getClientChildPage(this.currentClientData)">搜索
          </el-button>
          <el-button type="success" style="" @click="importData">导入</el-button>
          <el-button type="success" style="" @click="exportData">导出</el-button>
        </div>
        <el-table :row-style="{ height: '77px' }" :data="tableData" border style="width: calc(100vw - 530px);height: 70vh; margin: 20px 25px 0px 0px">
          <el-table-column prop="id" label="ID" width="100"/>
          <el-table-column prop="name" label="名称" width="150"/>
          <el-table-column prop="state" align="center" label="状态" width="100">
            <template #default="scope">
              <el-tag v-if="scope.row.state === '0'" type="success">正常</el-tag>
              <el-tag v-else-if="scope.row.state === '1'" type="warning">冻结</el-tag>
              <el-tag v-else-if="scope.row.state === '2'" type="danger">暂停使用</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="address" label="地址" width="250"/>
          <el-table-column prop="linkman" label="联系人" width="100"/>
          <el-table-column prop="teleLinkman" label="联系人电话" width="120"/>
          <el-table-column prop="receptionist" label="值班员" width="100"/>
          <el-table-column prop="teleReceptionist" label="值班员电话" width="120"/>
          <el-table-column prop="pcId" label="上级单位ID" width="100"/>
          <el-table-column v-if="this.retrieve === 0" prop="pcName" label="上级单位名称" width="200"/>
          <el-table-column prop="organization" label="组织ID" width="100"/>
          <el-table-column v-if="this.retrieve === 0" prop="organizationName" label="组织" width="300"/>
          <el-table-column prop="photo" label="照片" width="auto">
            <template #default="scope">
              <img v-if="scope.row.photo" :src="scope.row.photo" width="50" style="max-height: 77px" alt="photo"/>
            </template>
          </el-table-column>
          <el-table-column prop="logo" label="logo" width="auto">
            <template #default="scope">
              <img v-if="scope.row.logo" :src="scope.row.logo" width="50" style="max-height: 60px" alt="logo"/>
            </template>
          </el-table-column>
          <el-table-column prop="explanation" fit="false" label="说明" width="auto"/>
          <el-table-column prop="dispatcher" label="接警人" width="100"/>
          <el-table-column prop="teleDispatcher" label="接警人电话" width="120"/>
          <el-table-column prop="dispatchSupervisor" label="接警领导" width="100"/>
          <el-table-column prop="teleDispatchSupervisor" label="接警领导电话" width="120"/>
          <el-table-column align="center" label="操作" fixed="right" width="250" style="margin-right: 50px">
            <template v-slot="scope">
              <el-button type="primary" size="small" icon="Edit" @click="editItem(scope.row)">编辑</el-button>
              <el-button type="primary" size="small" icon="Edit" @click="detail(scope.row)">详情</el-button>
              <el-button v-if="this.userInformation.role === 1" type="danger" size="small" icon="Delete" @click="deleteItem(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination
            style="margin-top: 10px"
            :current-page="currentPage"
            :page-size="pageSize"
            :page-sizes="[10, 20, 30, 50]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            :background="true"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <el-dialog v-model="isDetail" :show-close="false" width="800">
      <el-descriptions
          class="margin-top"
          :column="2"
          size="default"
          :title="form.name"
          border
      >
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">
              <span class="iconfont icon-kehumingcheng"></span>
              名称
            </div>
          </template>
          {{ form.name }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">
              <span class="iconfont icon-zhaopian1"></span>
              照片
            </div>
          </template>
          <img v-if="form.photo" @click="handlePictureCardPreview(form.photo)" width="50" style="max-height: 100px" :src="form.photo" alt="photo">
          <img v-else width="50" style="max-height: 100px">
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">
              <span class="iconfont icon-icon_zhuangtai"></span>
              状态
            </div>
          </template>
          <el-tag v-if="form.state === '0'" type="success">正常</el-tag>
          <el-tag v-else-if="form.state === '1'" type="warning">冻结</el-tag>
          <el-tag v-else-if="form.state === '2'" type="danger">暂停使用</el-tag>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">
              <span class="iconfont icon-zhaopian1"></span>
              logo
            </div>
          </template>
          <img v-if="form.logo" width="50" @click="handlePictureCardPreview(form.logo)" style="max-height: 100px" :src="form.logo" alt="logo">
          <img v-else width="50" style="max-height: 100px">
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">
              <el-icon><User /></el-icon>
              联系人
            </div>
          </template>
          {{form.linkman}}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">
              <el-icon><Iphone /></el-icon>
              联系人电话
            </div>
          </template>
          {{ form.teleLinkman }}
        </el-descriptions-item>
        <el-descriptions-item
        span="2">
          <template #label>
            <div class="cell-item">
              <el-icon><Position /></el-icon>
              地址
            </div>
          </template>
          {{ form.address }}
        </el-descriptions-item>
        <el-descriptions-item
                v-if="this.retrieve === 0"
                span="2">
          <template #label>
            <div class="cell-item">
              <span class="iconfont icon-kehumingcheng"></span>
              上级单位名称
            </div>
          </template>
          {{ form.pcName }}
        </el-descriptions-item>
        <el-descriptions-item
                v-if="this.retrieve === 0"
                span="2">
          <template #label>
            <div class="cell-item">
              <span class="iconfont icon-zuzhijigou"></span>
              组织
            </div>
          </template>
          {{ form.organizationName }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">
              <el-icon><User /></el-icon>
              值班员
            </div>
          </template>
          {{form.receptionist}}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">
              <el-icon><Iphone /></el-icon>
              值班员电话
            </div>
          </template>
          {{form.teleReceptionist}}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">
              <el-icon><User /></el-icon>
              接警人
            </div>
          </template>
          {{form.dispatcher}}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">
              <el-icon><Iphone /></el-icon>
              接警人电话
            </div>
          </template>
          {{form.teleDispatcher}}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">
              <el-icon><User /></el-icon>
              接警领导
            </div>
          </template>
          {{form.dispatchSupervisor}}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">
              <el-icon><Iphone /></el-icon>
              接警领导电话
            </div>
          </template>
          {{form.teleDispatchSupervisor}}
        </el-descriptions-item>
        <el-descriptions-item
            span="4">
          <template #label>
            <div class="cell-item">
              <el-icon><Position /></el-icon>
              点位图
            </div>
          </template>
          <div style="padding: 10px; border-radius: 5px;" v-if="form.pointMap">
            <template v-for="(url, index) in form.pointMap.split(',')" :key="index">
              <div style="display: inline-block; margin-right: 10px; position: relative;">
                <img :src="url.trim()" @click="handlePictureCardPreview(url)" alt="点位图" style="max-width: 100px; border-radius: 4px;" />
              </div>
            </template>
          </div>
        </el-descriptions-item>
        <el-descriptions-item
            span="4">
          <template #label>
            <div class="cell-item">
              <span class="iconfont icon-ziyuan"></span>
              说明
            </div>
          </template>
          {{ form.explanation }}
        </el-descriptions-item>
      </el-descriptions>
      <div style="text-align: center;margin-top: 10px">
        <el-button @click="closeDetail">关闭</el-button>
      </div>
    </el-dialog >
<!--    单位操作-->
    <el-dialog :close-on-click-modal="false" v-model="operationItemDialog" :show-close="false" title="单位操作" width="700">
      <el-form :inline="true" :model="form" :rules="formRules" ref="form" label-position="right" class="demo-roleForm">
        <el-form-item label="单位名称" prop="name" class="formItem">
          <el-input v-model="form.name" class="input-size" placeholder="单位名称"></el-input>
        </el-form-item>
        <el-form-item width="300px" v-if="this.isEdit === false">
        </el-form-item>
        <el-form-item v-if="this.isEdit === true" label="状态" prop="state" class="formItem">
          <el-select  v-model="form.state" placeholder="请选择状态">
            <el-option
                v-for="item in statOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="&nbsp;&nbsp;&nbsp;照片" prop="photo" class="formItem">
          <el-upload
              class="avatar-uploader"
              :action="'/api/files/upload'"
              :on-success="photoHandleSuccess"
              :on-error="photoHandleError"
              :show-file-list="false"
          >
            <template #tip>
              <div class="el-upload__tip">
                {{ photoType() }}文件应小于{{ fileSizeLimit() }}
              </div>
            </template>
            <img width="100" height="100" v-if="form.photo" :src="form.photo" class="avatar">
            <img width="100" height="100" v-else>
          </el-upload>
        </el-form-item>
        <el-form-item label="&nbsp;&nbsp;&nbsp;&nbsp;logo" prop="logo" class="formItem">
          <el-upload
              class="avatar-uploader"
              :action="'/api/files/upload'"
              :on-success="logoHandleSuccess"
              :on-error="photoHandleError"
              :show-file-list="false"
          >
            <img width="100" height="100" v-if="form.logo" :src="form.logo" class="avatar">
            <img width="100" height="100" v-else>
          </el-upload>
        </el-form-item>
        <el-form-item label="点位图" prop="pointMap" style="width: 100%" class="formItem">
          <el-upload
              :on-error="photoHandleError"
              :action="'/api/files/upload'"
              :on-success="pointMapUpload"
              list-type="picture-card"
              :file-list="pointMapList"
          >
            <template #tip>
              <div class="el-upload__tip">
                {{ photoType() }}文件应小于{{ fileSizeLimit() }}
              </div>
            </template>
            <el-icon><Plus /></el-icon>
            <template #file="{ file }" style="display:flex;text-align: center;justify-content: center">
              <div>
                <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
                <span class="el-upload-list__item-actions">
                  <span
                      class="el-upload-list__item-preview"
                      @click="handlePictureCardPreview(file.url)"
                  >
                    <el-icon><zoom-in /></el-icon>
                  </span>
                  <span
                      class="el-upload-list__item-delete"
                      @click="handleRemove(file)"
                  >
                    <el-icon><Delete /></el-icon>
                  </span>
                </span>
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="地图位置" prop="address">
          <div style="display: flex">
            <el-input type="text" placeholder="请选择地址" v-model="form.address" disabled/>
            <el-button style="margin-left: 10px" @click="this.$store.state.mapDialog=true" type="primary">
              选择地址
            </el-button>
          </div>
        </el-form-item>
        <el-form-item label="地址经度" prop="longitude">
          <el-input class="input-size" v-model="form.longitude" placeholder="请选择地址" disabled/>
        </el-form-item>
        <el-form-item label="地址纬度" prop="latitude">
          <el-input class="input-size" v-model="form.latitude" placeholder="请选择地址" disabled/>
        </el-form-item>
        <el-form-item label="组织" style="width: 300px" prop="organization">
        <span style="width: 250px;margin-right: 15px">
           <OrganizationTree
                   v-model="form.organization"/>
        </span>
        </el-form-item>
        <el-form-item label="上级单位名称" prop="clientId">
          <el-select style="width: 190px" v-model="form.pcId" filterable clearable placeholder="选择上级单位名称">
            <el-option
                    v-for="item in clientOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系人" prop="linkman" class="formItem">
          <el-input v-model="form.linkman" class="input-size" placeholder="联系人"></el-input>
        </el-form-item>
        <el-form-item label="联系人电话" prop="teleLinkman" class="formItem">
          <el-input v-model="form.teleLinkman" class="input-size" placeholder="联系人电话"></el-input>
        </el-form-item>
        <div v-if="form.dispatchers?.length>0" v-for="(dispatcher, index) in form.dispatchers" :key="index" style="display: flex">
          <el-form-item :label="'接警人 ' + (index + 1)" :prop="'dispatcher' + index+1">
            <el-input
                v-model="form.dispatchers[index]"
                style="width: 160px"
                placeholder="接警人"
            ></el-input>
          </el-form-item>
          <el-form-item :label="'接警人 ' + (index + 1)+'电话'" :prop="'teleDispatchers' + index+1">
            <el-input
                v-model="form.teleDispatchers[index]"
                style="width: 160px"
                placeholder="接警人电话"
            ></el-input>
          </el-form-item>
          <el-button v-if="form.dispatchers.length!==1" @click="remoDispatcher(index)" type="danger">删除</el-button>
          <el-button @click="addDispatcher" v-if="index===form.dispatchers.length-1" type="primary">添加接警人</el-button>
        </div>
        <div v-else style="display: flex">
          <el-form-item label="接警人" prop="dispatcher" class="formItem">
            <el-input v-model="form.dispatcher" class="input-size" placeholder="接警人"></el-input>
          </el-form-item>
          <el-form-item label="接警人电话" prop="teleDispatcher" class="formItem">
            <el-input v-model="form.teleDispatcher" class="input-size" placeholder="接警人电话"></el-input>
          </el-form-item>
          <el-button @click="addDispatcher" type="primary">添加接警人</el-button>
        </div>
        <div v-if="form.receptionists?.length>0" v-for="(receptionist, index) in form.receptionists" :key="index" style="display: flex">
          <el-form-item :label="'值班员 ' + (index + 1)" :prop="'receptionists' + index+1">
            <el-input
                v-model="form.receptionists[index]"
                style="width: 160px"
                placeholder="值班员"
            ></el-input>
          </el-form-item>
          <el-form-item :label="'值班员 ' + (index + 1)+'电话'" :prop="'teleReceptionists' + index+1">
            <el-input
                v-model="form.teleReceptionists[index]"
                style="width: 160px"
                placeholder="值班员电话"
            ></el-input>
          </el-form-item>
          <el-button v-if="form.receptionists.length!==1" @click="removeReceptionist(index)" type="danger">删除</el-button>
          <el-button @click="addReceptionist" v-if="index===form.receptionists.length-1" type="primary">添加值班员</el-button>
        </div>
        <div v-else style="display: flex">
          <el-form-item label="值班员" prop="receptionist">
            <el-input v-model="form.receptionist" style="width: 160px" placeholder="值班员"></el-input>
          </el-form-item>
          <el-form-item label="值班员电话" prop="teleReceptionist" >
            <el-input v-model="form.teleReceptionist" style="width: 160px" placeholder="值班员电话"></el-input>
          </el-form-item>
          <el-button @click="addReceptionist" type="primary">添加值班员</el-button>
        </div>
        <el-form-item label="接警领导" prop="dispatchSupervisor" class="formItem">
          <el-input v-model="form.dispatchSupervisor" class="input-size" placeholder="接警领导"></el-input>
        </el-form-item>
        <el-form-item label="接警领导电话" prop="teleDispatchSupervisor" class="formItem">
          <el-input v-model="form.teleDispatchSupervisor" class="input-size" placeholder="接警领导电话"></el-input>
        </el-form-item>
        <el-form-item label="物联云API密钥" prop="monitorkey" class="formItem">
          <el-input v-model="form.monitorkey" class="input-size" placeholder="物联云API密钥"></el-input>
        </el-form-item>
        <el-form-item label="&nbsp;&nbsp;&nbsp;说明" style="width: 635px" prop="explanation">
          <el-input type="textarea" placeholder="请填写说明" v-model="form.explanation"/>
        </el-form-item>
        <el-form-item style="text-align: right">
          <el-button  type="primary" @click="submitForm('form')">提交</el-button>
          <el-button style="color: #606266" @click="reset('form')">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog :close-on-click-modal="false" v-model="this.$store.state.mapDialog" style="width: 50%;">
      <MapAddressSelect ref="bmapAddressSelect" @confirmMapAddress="confirmMapAddress"></MapAddressSelect>
    </el-dialog>
<!--    节点操作-->
    <el-dialog :close-on-click-modal="false" v-model="operationNodeDialog" title="操作组织" style="width: 50%;">
      <el-form :model="nodeData" :rules="nodeDataRules" ref="nodeData" label-width="120px" label-position="right" class="demo-roleForm">
        <el-form-item label="名称" prop="name" style="width: 90%">
          <el-input v-model="nodeData.name" class="input-size" placeholder="请输入组织名称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button style="font-size: 12px" type="primary" @click="submitNode('nodeData')">提交</el-button>
          <el-button style="font-size: 12px;color: #606266" @click="reset('nodeData')">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <div v-if="dialogVisible" class="modal" @click="closeModal">
      <div class="modal-content" @click.stop>
        <!-- Close button -->
        <button class="close-btn" @click="closeModal">X</button>
        <img :src="dialogImageUrl" alt="" class="enlarged-image" :style="{ transform: 'scale(' + zoomLevel + ')'}" @wheel="handleZoom">
      </div>
    </div>
    <el-dialog title="导入" v-model="dialogImportVisible" width="520px">
      <el-form label-position="right" label-width="100px">
        <el-form-item label="模板下载:" padding-top:10px>
          <el-button type="primary" size="small" style="" @click="exportTemplate">单位信息</el-button>
        </el-form-item>
        <el-form-item label="文件" padding-top:-20px>
          <el-upload :headers="headers"
                           :multiple="false"
                     :on-success="onUploadSuccess"
                     :on-error="onUploadError"
                     :action="serverIp+'/client/importData'"
                     class="upload-demo">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传xlsx文件</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogImportVisible = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import request from "@/utils/request.js";
import MapAddressSelect from "@/components/BMapAddressSelect/MapAddressSelect.vue";
import Image from "@/views/homeComponents/Image.vue";
import {Delete, Download, Iphone, Plus, Position, ZoomIn} from "@element-plus/icons-vue";
import {ElIcon} from "element-plus";
import OrganizationTree from "@/components/OrganizationTree.vue";
import ClientTree from "@/components/ClientTree.vue";
import {nextTick, ref} from "vue";
import Breadcrumb from "@/components/Breadcrumb.vue";
import {fileSizeLimit, photoType} from "@/assets/globalJS.js";
import {serverIp} from "../../../public/static/config"
import { toRaw } from 'vue'

export default {
  name: "Client",
  components: {Plus, Delete, Download, ZoomIn, Breadcrumb, OrganizationTree, ClientTree, Iphone, Position, Image, MapAddressSelect},
  data() {
    return {
      retrieve: 0,
      zoomLevel: 1,  // Initial zoom level
      serverIp,
                headers: {
                    token:  JSON.parse(localStorage.getItem('user')).token,
                },
      dialogImportVisible: false,
      isEdit: false,
      level : 0,
      organizationId: "",
      userInformation:JSON.parse(localStorage.getItem("user")),
      value:'',
      searchName:"", // 搜索框
      searchAddress:'',
      addText: "省组织",  // 按钮显示
      isDetail:false,
      operationNodeDialog: false, // 节点操作弹窗
      operationItemDialog: false, // 单位操作弹窗
      operationPoingMapDialog:false,// 点位图操作弹窗
      pointMapList:[], // 当前操作的点位图图片列表
      mapDialog:false,
      dialogImageUrl:"",
      dialogVisible:false,
      nodeParent:[],
      currentData: {}, // 当前选中节点
      currentNode: {},
      currentClientData: {},
      currentClientNode: {},
      tableData: [],  // 单位表格数据
      formRules: {       // 单位操作表单
        name: [
          {required: true, message: '请输入名称', trigger: 'blur'},
        ],
        state: [
          {required: true, message: '请选择状态', trigger: 'blur'},
        ],
        address: [
          {required: true, message: '请输入地址', trigger: 'blur'},
        ],
        linkman: [
          {required: true, message: '请输入联系人', trigger: 'blur'},
        ],
        teleLinkman: [
          {required: true, message: '请输入联系人电话', trigger: 'blur'},
        ],
        // receptionist: [
        //   {required: true, message: '请输入值班员', trigger: 'blur'},
        // ],
        // teleReceptionist: [
        //   {required: true, message: '请输入值班员电话', trigger: 'blur'},
        // ],
        // dispatcher: [
        //   {required: true, message: '请输入接警人', trigger: 'blur'},
        // ],
        // teleDispatcher: [
        //   {required: true, message: '请输入接警人电话', trigger: 'blur'},
        // ],
        // dispatchSupervisor: [
        //   {required: true, message: '请输入接警领导', trigger: 'blur'},
        // ],
        // teleDispatchSupervisor: [
        //   {required: true, message: '请输入接警领导电话', trigger: 'blur'},
        // ],
        organization:[
          {required: true, message: '请选择组织', trigger: 'blur'},
        ]
      },
      nodeDataRules: {
        name: [
          {required: true, message: '请输入名称', trigger: 'blur'},
        ],
      },
      form:{},  // 操作单位数据
      nodeData:{}, // 操作节点数据
      currentPage: 1,
      pageSize: 10,
      total: 0,
      treeData: [],
      clientTreeData: [],
      defaultProps: {
        children: 'children',
        label: 'name',
        value: 'name'
      },
      clientDefaultProps: {
        children: 'children',
        label: 'name',
        value: 'name'
      },
      statOptions:[
        {
          value: '0',
          label: '正常'
        }, {
          value: '1',
          label: '冻结'
        }, {
          value: '2',
          label: '暂停使用'
        }
      ],
      clientOptions: [],
      filterText: '',
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    if (this.userInformation.organization){
      this.level=this.userInformation.level
      this.organizationId = this.userInformation.organization
    }
    this.getOrganization()
    this.load()
    this.getClientOptions()
  },
  methods: {
    checkRetrieve() {
      if (this.retrieve === 0) {
        this.retrieve = 1
        this.currentPage = 1
        this.searchName = ''
        this.searchAddress = ''
        this.currentClientData = null
        this.currentClientNode=null
        this.getFirstClient()
        this.getClientPage()
      } else if (this.retrieve === 1) {
        this.retrieve = 0
        this.currentPage = 1
        this.currentData.level=JSON.parse(localStorage.getItem("user")).level
        this.currentData.id = JSON.parse(localStorage.getItem("user")).organization
        this.searchName = ''
        this.searchAddress = ''
        this.getOrganization()
        this.load()
      }
    },
    getClientOptions() {
      let level = JSON.parse(localStorage.getItem("user")).level
      let organizationId = JSON.parse(localStorage.getItem("user")).organization
      let isAllClient = JSON.parse(localStorage.getItem("user")).isAllClient;
      let clientIds;
      if (isAllClient === "1") {
        clientIds = JSON.parse(localStorage.getItem("user")).clientIds;
      } else {
        clientIds = [];
      }
      request.get("/client/listbyName?organizationId=" + organizationId + "&level=" + level + "&isAllClient=" + isAllClient + "&clientIds=" + clientIds).then(res => {
        this.clientOptions = res.data
      })
    },
    confirmMapAddress(addressInfo) {
      if (addressInfo.province !== undefined) {
        this.form.address = addressInfo.province + addressInfo.city + addressInfo.district + addressInfo.address
        this.form.latitude = addressInfo.latitude
        this.form.longitude = addressInfo.longitude
      }
    },
    importData() {
      this.dialogImportVisible = true;
    },
    onUploadSuccess() {
      this.$message.success('上传成功');
      this.dialogImportVisible = false;
      location.reload();
    },
    onUploadError(){
      this.$message.error('上传失败');
    },
    // 模板下载
    exportTemplate() {
      window.location.href = '../xlsx/client.xlsx'
    },
    exportData() {
      let level = JSON.parse(localStorage.getItem("user")).level
      if (this.currentData.level!==undefined){
        level=this.currentData.level
      }
      let isAllClient = this.userInformation.isAllClient;
      let clientIds;
      if (isAllClient === "1") {
        clientIds = Object.values(this.userInformation.clientIds);
      } else {
        clientIds = [];
      }
      window.open(serverIp + "/client/export?level="+
      this.level+"&organizationId="+this.organizationId+"&name="+this.searchName+"&address="+this.searchAddress+"&isAllClient="+isAllClient+"&clientIds="+clientIds);
    },
    exportOrginData() {
      window.open(serverIp + "/organization/export");
    },
    photoType() {
      return photoType
    },
    fileSizeLimit() {
      return fileSizeLimit
    },
    photoHandleError(){
      this.$message.error("上传文件大小请勿超过"+fileSizeLimit)
    },
    // 添加
    addItem(){
      this.operationItemDialog = true;
    },
    // 编辑
    editItem(scope){
      this.isEdit = true
      Object.assign(this.form,scope)
      this.splitReceptionist()
      this.splitDispatcher()
      this.initPointMapList()
      this.operationItemDialog=true
    },
    // 值班员
    splitReceptionist(){
      this.form.receptionists = this.form.receptionist ? this.form.receptionist.split(",") : [];
      this.form.teleReceptionists = this.form.teleReceptionist ? this.form.teleReceptionist.split(",") : [];
    },
    // 值班员
    mergeReceptionist(){
      if (this.form.receptionists!==undefined){
        this.form.receptionists.forEach((item,index)=>{
          if (index!==0){
            this.form.receptionist=this.form.receptionist+","+item
          }else {
            this.form.receptionist=item
          }
        })
        this.form.teleReceptionists.forEach((item,index)=>{
          if (index!==0){
            this.form.teleReceptionist=this.form.teleReceptionist+","+item
          }else {
            this.form.teleReceptionist=item
          }
        })
      }
    },
    // 值班员
    addReceptionist() {
      this.mergeReceptionist()
      this.form.receptionist=this.form.receptionist+','; // 添加一个新的空值班员
      this.form.teleReceptionist=this.form.teleReceptionist+','; // 添加一个新的空值班员
      this.splitReceptionist()
    },
    // 值班员
    removeReceptionist(index) {
      if (this.form.receptionists.length > 1) {
        this.form.receptionists.splice(index, 1); // 删除指定的值班员
        this.form.teleReceptionists.splice(index, 1); // 删除指定的值班员
      } else {
        this.$message.warning('至少保留一个值班员'); // 至少保留一个值班员
      }
      this.mergeReceptionist()
    },
    // 接警员
    splitDispatcher(){
      this.form.dispatchers = this.form.dispatcher ? this.form.dispatcher.split(",") : [];
      this.form.teleDispatchers = this.form.teleDispatcher ? this.form.teleDispatcher.split(",") : [];
    },
    // 接警员
    mergeDispatcher(){
      if (this.form.dispatchers!==undefined){
        this.form.dispatchers.forEach((item,index)=>{
          if (index!==0){
            this.form.dispatcher=this.form.dispatcher+","+item
          }else {
            this.form.dispatcher=item
          }
        })
        this.form.teleDispatchers.forEach((item,index)=>{
          if (index!==0){
            this.form.teleDispatcher=this.form.teleDispatcher+","+item
          }else {
            this.form.teleDispatcher=item
          }
        })
      }
    },
    // 接警员
    addDispatcher() {
      this.mergeDispatcher()
      this.form.dispatcher=this.form.dispatcher+','; // 添加一个新的空值班员
      this.form.teleDispatcher=this.form.teleDispatcher+','; // 添加一个新的空值班员
      this.splitDispatcher()
    },
    // 接警员
    remoDispatcher(index) {
      if (this.form.dispatchers.length > 1) {
        this.form.dispatchers.splice(index, 1); // 删除指定的值班员
        this.form.teleDispatchers.splice(index, 1); // 删除指定的值班员
      } else {
        this.$message.warning('至少保留一个值班员'); // 至少保留一个值班员
      }
      this.mergeReceptionist()
    },
    detail(scope){
      this.form=scope;
      this.isDetail=true;
    },
    // 提交
    submitForm(val){
      this.mergeReceptionist()
      this.mergeDispatcher()
      this.$refs[val].validate((valid) => {
        if (valid) {
          request.post("/client/edit",this.form).then(res=>{
            if (res.code==='200'){
              this.operationItemDialog=false
              this.isEdit=false
              this.load()
              this.form={}
              this.$message({
                message:"成功",
                type:"success"
              })
              this.load()
            }else {
              this.$message.error("操作失败"+res.msg)
            }
          })
        }
      })
    },
    // 关闭查看详情
    closeDetail(){
      this.isDetail=false
      this.form={}
    },
    // 取消
    reset(val){
      this.operationItemDialog = false;
      this.operationNodeDialog = false;
      this.isEdit=false
      this.form={};
      this.pointMapList=[]
      this.nodeData={};
      this.$refs[val].clearValidate();
    },
    handleSizeChange(pageSize) {   // 改变当前每页的个数触发
      this.pageSize = pageSize
      if(this.retrieve === 0) {
        this.load()
      } else {
        if(this.currentClientData === null) {
          this.getClientPage()
        } else {
          this.getClientChildPage(this.currentClientData)
        }
      }
    },
    handleCurrentChange(pageNum) {  // 改变当前页码触发
      this.currentPage = pageNum
      if(this.retrieve === 0) {
        this.load()
      } else {
        if(this.currentClientData === null) {
          this.getClientPage()
        } else {
          this.getClientChildPage(this.currentClientData)
        }
      }
    },
    // 删除
    deleteItem(scope){
      this.$confirm('是否确定删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        request.get("/client/delete/"+scope).then(res=>{
          if (res.code==='200'){
            this.$message.success("成功")
            this.load()
          }else {
            this.$message.error("删除失败"+res.msg)
          }
        })
      })
          .catch(() => {
          });
    },
    // 搜索及初始化
    load(){
      if (this.currentData.id!==undefined){
        this.level = this.currentData.level
        this.organizationId=this.currentData.id
      }
      let isAllClient = this.userInformation.isAllClient;
      let clientIds;
      if (isAllClient === "1") {
        clientIds = Object.values(this.userInformation.clientIds);
      } else {
        clientIds = [];
      }
      request.get("/client/listbyorgan?pageNum=" + this.currentPage + "&pageSize=" + this.pageSize+"&level="+
          this.level+"&organizationId="+this.organizationId+"&name="+this.searchName+"&address="+this.searchAddress+"&isAllClient="+isAllClient+"&clientIds="+clientIds).then(res => {
          this.tableData = res.data.record;
          this.total = res.data.total;
      })
    },
    // 获取所有一级组织
    async getFirstLevel() {
      try {
        const res = await request.get("/organization/findHighOrgan");
        if (res.data.length>0){
          this.treeData = res.data;
          await nextTick(() => {
            this.$refs['tree'].setCurrentKey(this.treeData.at(0).id)
          })
          this.currentChanged(this.treeData.at(0))
        }else {
          this.$message.error("无数据")
        }
      }catch (error) {
        this.$message.info("获取一级组织失败"+error)
      }
    },
    // 获取 最高级组织
    async getOrganization() {
      try {
        const res = await request.get("/organization/" + JSON.parse(localStorage.getItem("user")).organization);
        if (res.data) {
          if (this.treeData.length===0){
            this.treeData.push(res.data);
            await nextTick(() => {
              this.$refs['tree'].setCurrentKey(this.treeData.at(0).id)
            })
            this.currentChanged(this.treeData.at(0))
          }
        } else {
          this.$message.error("无数据");
        }
      } catch (error) {
        this.$message.error("获取组织失败" + error);
      }
    },
    // 获取所有一级单位
    async getFirstClient() {
      try {
        let level = JSON.parse(localStorage.getItem("user")).level
        let organizationId = JSON.parse(localStorage.getItem("user")).organization
        let isAllClient = JSON.parse(localStorage.getItem("user")).isAllClient;
        let userId = JSON.parse(localStorage.getItem("user")).id;
        await request.get("/client/getSubordClient?level="+
                level+"&organizationId="+organizationId+"&name="+this.searchName+"&address="+this.searchAddress+"&isAllClient="+isAllClient+"&userId="+userId).then(res => {
          if (res.data.total>0){
            this.clientTreeData = res.data.record;
          }else {
            this.$message.error("无数据")
          }
        })
      }catch (error) {
        this.$message.info("获取一级单位失败"+error)
      }
    },
    getClientPage() {
      let level = JSON.parse(localStorage.getItem("user")).level
      let organizationId = JSON.parse(localStorage.getItem("user")).organization
      let isAllClient = JSON.parse(localStorage.getItem("user")).isAllClient;
      let userId = JSON.parse(localStorage.getItem("user")).id;
      request.get("/client/getSubordClient?pageNum=" + this.currentPage + "&pageSize=" + this.pageSize+"&level="+
              level+"&organizationId="+organizationId+"&name="+this.searchName+"&address="+this.searchAddress+"&isAllClient="+isAllClient+"&userId="+userId).then(res => {
        if (res.data.total>0){
          this.tableData = res.data.record;
          this.total = res.data.total;
        }else {
          this.$message.error("无数据")
        }
      })
    },
    // 节点新增按钮
    addNode(){
      this.operationNodeDialog=true;
    },
    // 新增节点数据提交
    submitNode(val){
      this.$refs[val].validate((valid) => {
        if (valid) {
          // 新增
          if (this.nodeData.id===undefined){
            // 省级，设置层级即可
            if (this.currentData.level===0){
              this.nodeData.level = 0;
              this.nodeData.pid=1;
            }else { // 其他级，设置层级及父id
              this.nodeData.pid = this.currentData.id
              this.nodeData.level = this.currentData.level+1;
            }
          }
          request.post("/organization/edit",this.nodeData).then(res=>{
            if (res.code==='200'){
              // 更新时直接赋值
              if (this.nodeData.id!==undefined){
                this.currentData.name=this.nodeData.name
              }else {
              }
              // 节点修改成功 重置其他节点获取
              this.$store.commit("resetOrganization")
              this.reset(val);
              this.$message({
                message:"成功",
                type:"success"
              })
              this.currentData.children=[]
              if (this.nodeData.level===0){
                this.getOrganization()
              }
            }else {
              this.$message.error(res.msg)
            }
          })
        }
      })
    },
    editNode(){
      // 赋值
      Object.assign(this.nodeData,this.currentData)
      this.operationNodeDialog=true
    },
    // 删除节点
    async deleteNode() {
      try {
        this.$confirm('是否确定删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          const res = await request.get("/organization/delete?organizationId=" + this.currentData.id + "&level=" + this.currentData.level);
          if (res.code === '200') {
            // 节点修改成功 重置其他节点获取
            this.$store.commit("resetOrganization")
            // 树的数据处理
            if (this.currentNode.level!==1){
              this.currentNode.parent.childNodes.forEach((data,index)=>{
                if (data.data.id===this.currentData.id){
                  this.currentNode.parent.childNodes.splice(index, 1);
                }
              })
            }else {
              this.getOrganization()
            }
            this.currentChanged(this.currentNode.parent.data)
            this.$message.success("删除成功")
          } else {
            this.$message.error("操作失败" + res.msg)
          }
        })
      }catch (e) {
      }
    },
    // 树节点选中发生改变
    currentChanged(data,node) {
      this.currentData = data
      this.currentNode=node
      this.load()
      switch (data.level) {
        case 0:
          this.addText="省组织";
          break;
        case 1:
          this.addText="市组织";
          break;
        case 2:
          this.addText="区县组织";
          break;
        case 3:
          this.addText="小区";
          break;
        case 4:
          this.addText="栋";
          break;
        case 5:
          this.addText="单元";
          break;
        case 6:
          this.addText="层";
          break;
        case 7:
          this.addText="房";
      }
      // 获取子节点
      this.getNodeChildren(data)
    },
    async getNodeChildren(data) {
      if (data.children && data.children.length > 0) {
        return;
      }
      try {
        const res = await request.get(`/organization/findOrganizations/${data.id}`);
        if (res.data.length > 0) {
          data.children = res.data;
        }
      } catch (error) {
        this.$message.error("获取子节点数据失败：" + error);
      }
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },

    // 单位树节点选中发生改变
    currentClientChanged(data,node) {
      this.currentClientData = data
      this.currentClientNode=node
      this.searchName = ''
      this.searchAddress = ''
      this.getClientChildPage(data)
      this.loadByClient(data)
    },
    loadByClient(data) {
      try {
        request.get("/client/findChildClient?pcId=" + data.id).then(res => {
          if (res.data.total > 0) {
            data.children = res.data.record;
          }
        })
      } catch (error) {
        this.$message.error("获取单位子节点数据失败：" + error);
      }
    },
    getClientChildPage(data) {
      try {
        request.get("/client/findChildClient?pageNum=" + this.currentPage + "&pageSize=" + this.pageSize+"&pcId=" + data.id +"&name="+this.searchName+"&address="+this.searchAddress).then(res => {
          if (res.data.total > 0) {
            this.tableData = res.data.record;
            this.total = res.data.total;
          } else {
            this.tableData = []
            this.tableData.push(JSON.parse(JSON.stringify(this.currentClientData)))
          }
        })
      } catch (error) {
        this.$message.error("获取单位子节点数据失败：" + error);
      }
    },
    // logo上传
    logoHandleSuccess(response) {
      this.form.logo=`/api/file/download${response}`
    },
    // photo上传
    photoHandleSuccess(response) {
      this.form.photo=`/api/file/download${response}`
    },
    initPointMapList() {
      this.pointMapList = this.form.pointMap ? this.form.pointMap.split(',').map(url =>{return {url}}) : [];
    },
    // 删除一张点位图
    removeImage(index) {
      const images = this.form.pointMap.split(',');
      images.splice(index, 1); // 删除选中的图片
      this.form.pointMap = images.join(','); // 更新 pointMap 字符串
    },
    handleRemove(file) {
      const index = this.pointMapList.indexOf(file);
      if (index !== -1) {
        const images = this.form.pointMap.split(',');
        images.splice(index, 1); // 删除选中的图片
        this.form.pointMap = images.join(','); // 更新 pointMap 字符串
        this.pointMapList.splice(index, 1);
      }
    },
    handleZoom(event) {
      event.preventDefault(); // 防止页面滚动

      // 根据滚轮方向调整缩放级别
      if (event.deltaY < 0) {
        this.zoomLevel = Math.min(this.zoomLevel + 0.1, 3); // 最大缩放到3倍
      } else {
        this.zoomLevel = Math.max(this.zoomLevel - 0.1, 1); // 最小缩放到1倍
      }
    },
    handlePictureCardPreview(item) {
      this.dialogImageUrl = item;
      this.dialogVisible = true;
    },
    closeModal() {
      this.dialogImageUrl = ''
      this.dialogVisible = false
      this.zoomLevel = 1; // 重置缩放级别
    },
    pointMapUpload(response){
      // this.pointMapList = this.form.pointMap.split(',');

      if (this.pointMapList.length===0){
        this.form.pointMap=`/api/file/download${response}`
      }else {
        this.form.pointMap=this.form.pointMap+`,/api/file/download${response}`
      }
      this.initPointMapList()
      console.log(this.pointMapList)
      console.log(this.form.pointMap)
    },
  }
}
</script>

<style scoped>
:deep(.el-table th .cell)  {
  font-weight: 700
}
:deep(.el-form-item__label) {
  font-size: 14px;
  font-weight: 700
}
.input-size {
  font-size: 13px;
}

.formItem{
  width: 45%;
}
.cell-item{
  width: 100%;
}
.custom-tree-node {
  display: flex;
  align-items: center;
}
.node-label {
  flex-grow: 1;
  margin-left: 8px;
}
.el-tree-node__expand-icon {
  margin-left: 0;
  margin-right: 5px;
  cursor: pointer;
}
.modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw; /* 使用视口宽度 */
  height: 100vh; /* 使用视口高度 */
  background-color: rgba(0, 0, 0, 0.9); /* 更深的半透明背景 */
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9000; /* 确保弹窗在最上层 */
}

.modal-content {
  position: relative; /* 相对定位，用于定位关闭按钮 */
  width: 100%; /* 弹窗内容宽度为100% */
  height: 100%; /* 弹窗内容高度为100% */
  display: flex;
  justify-content: center;
  align-items: center;
}

.close-btn {
  z-index: 9999;
  position: absolute;
  top: 20px; /* 离顶部距离 */
  right: 20px; /* 离右侧距离 */
  background-color: transparent; /* 背景透明 */
  border: none;
  font-size: 24px; /* 字体大小 */
  cursor: pointer;
  color: red; /* 关闭按钮颜色 */
}

.close-btn:hover {
  color: red; /* 鼠标悬停时颜色变化 */
}

.enlarged-image {
  max-width: 100%; /* 确保图片不会超出弹窗边界 */
  max-height: 100%; /* 确保图片不会超出弹窗边界 */
  border-radius: 0; /* 去掉图片的圆角 */
  transition: transform 0.3s ease; /* 变换过渡效果 */
}


</style>
